package com.duing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.duing.dto.UserDTO;
import com.duing.entity.User;
import com.duing.enums.ErrorCode;
import com.duing.exception.BusinessException;
import com.duing.mapper.UserMapper;
import com.duing.service.UserService;
import com.duing.vo.UserBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;
    public void validateUser(User user){
        if(existsByName(user.getName())){
            throw new BusinessException(ErrorCode.DATA_EXISTS.getCode(), "该用户已存在");
        }
    }

    public boolean existsByName(String name){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        return baseMapper.selectCount(queryWrapper) > 0;
    }
    public List<UserBean> selectGroupByAge() {
        return userMapper.selectGroupByAge();
    }


    @Override
    public Page<User> getUsersByKeyword(int page, int size, UserDTO dto) {
        if(page <= 0 || size <= 0){
            throw new BusinessException(ErrorCode.PARAM_ERROR.getCode(), "分页参数错误");
        }
        Page pageParam = new Page<>(page, size);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        if(dto.getName() != null && !dto.getName().isEmpty()){
            queryWrapper.like("name", dto.getName());
        }
        if(dto.getAge() != null){
            queryWrapper.eq("age", dto.getAge());
        }
        if(dto.getJob() != null){
            queryWrapper.eq("job", dto.getJob());
        }
        if(dto.getId() != null){
            queryWrapper.eq("id", dto.getId());
        }
        return (Page<User>) baseMapper.selectPage(pageParam, queryWrapper);
    }
}
